﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZoneLineNew.Core.Utils {
    // <summary>
    /// 打印机工具类（.NET Framework 4.8）
    /// 用于获取系统中已安装的打印机名称列表及默认打印机
    /// </summary>
    public static class PrinterUtil {

        /// <summary>
        /// 获取所有已安装的打印机名称列表
        /// </summary>
        /// <returns>打印机名称列表（若无可返回空列表）</returns>
        public static List<string> GetAllPrinterNames() {
            List<string> printerNames = new List<string>();
            try {
                // 获取系统中所有已安装的打印机名称（包含本地和网络打印机）
                var installedPrinters = PrinterSettings.InstalledPrinters;

                // 转换为List<string>
                foreach (string printerName in installedPrinters) {
                    if (!string.IsNullOrWhiteSpace(printerName)) {
                        printerNames.Add(printerName);
                    }
                }
            } catch (Exception ex) {
                // 捕获异常（如权限不足、打印机服务异常等）
                throw new InvalidOperationException("获取打印机列表失败：" + ex.Message, ex);
            }
            return printerNames;
        }

        /// <summary>
        /// 获取系统默认打印机名称
        /// </summary>
        /// <returns>默认打印机名称（若无可返回null）</returns>
        public static string GetDefaultPrinterName() {
            try {
                // 遍历所有打印机，判断是否为默认打印机
                foreach (string item in PrinterSettings.InstalledPrinters) {
                    PrinterSettings settings = new PrinterSettings();
                    settings.PrinterName = item;//打印机名称
                    if (settings.IsDefaultPrinter) {
                        return item;
                    }
                }
                // 无默认打印机时返回null
                return null;
            } catch (Exception ex) {
                throw new InvalidOperationException("获取默认打印机失败：" + ex.Message, ex);
            }
        }
    }
}
